const express = require('express');
const { pool } = require('../config/db');
const { authMiddleware } = require('../middleware/auth');
const weaponService = require('../services/weaponService');

const router = express.Router();

/**
 * 将平面的战技指标数据转换为树形结构
 * @param {Array} flatData - 平面数据
 * @returns {Array} - 树形数据
 */
function buildSpecificationsTree(flatData) {
  if (!flatData || flatData.length === 0) {
    return [];
  }

  const map = {};
  const roots = [];

  // 创建映射，每个节点初始化children数组
  flatData.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  // 建立父子关系
  flatData.forEach(item => {
    const node = map[item.id];
    if (item.parent_id === null) {
      // 顶级节点
      roots.push(node);
    } else if (map[item.parent_id]) {
      // 子节点，添加到父节点的children中
      map[item.parent_id].children.push(node);
    }
  });

  // 清理空的children数组（可选，让JSON更简洁）
  function cleanEmptyChildren(nodes) {
    nodes.forEach(node => {
      if (node.children && node.children.length > 0) {
        cleanEmptyChildren(node.children);
      } else {
        delete node.children;
      }
    });
  }
  cleanEmptyChildren(roots);

  return roots;
}

// 所有接口都需要认证
router.use(authMiddleware);

/**
 * POST /api/weapons/import
 * 单条录入武器装备原始数据
 */
router.post('/import', async (req, res) => {
  try {
    const { name, description, dataSource } = req.body;

    if (!name || !description) {
      return res.status(400).json({
        success: false,
        message: '装备名称和介绍为必填项'
      });
    }

    console.log(`录入武器装备: ${name}`);

    const sql = `
      INSERT INTO raw_weapons (name, description, data_source)
      VALUES (?, ?, ?)
    `;

    const [result] = await pool.execute(sql, [
      name,
      description,
      dataSource || null
    ]);

    console.log(`✓ 录入成功，ID: ${result.insertId}`);

    res.json({
      success: true,
      message: '录入成功',
      id: result.insertId
    });
  } catch (error) {
    console.error('录入失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * GET /api/weapons/recent
 * 获取最近录入的记录
 */
router.get('/recent', async (req, res) => {
  try {
    const { limit = 10 } = req.query;

    const [records] = await pool.execute(
      'SELECT id, name, data_source, created_at FROM raw_weapons ORDER BY created_at DESC LIMIT ?',
      [parseInt(limit)]
    );

    res.json({
      success: true,
      data: records
    });
  } catch (error) {
    console.error('获取最近录入记录失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * GET /api/weapons/pending
 * 获取待处理记录列表
 */
router.get('/pending', async (req, res) => {
  try {
    const { page = 1, pageSize = 20 } = req.query;

    const result = await weaponService.getPendingRecords(
      parseInt(page),
      parseInt(pageSize)
    );

    res.json(result);
  } catch (error) {
    console.error('获取待处理记录失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * POST /api/weapons/process/:id
 * 处理单条记录
 */
router.post('/process/:id', async (req, res) => {
  try {
    const { id } = req.params;

    console.log(`开始处理装备记录，ID: ${id}`);

    // 获取原始记录
    const [records] = await pool.execute(
      'SELECT * FROM raw_weapons WHERE id = ?',
      [id]
    );

    if (records.length === 0) {
      return res.status(404).json({
        success: false,
        message: '记录不存在'
      });
    }

    const record = records[0];

    // 检查处理状态
    if (record.process_status === 'completed') {
      return res.json({
        success: false,
        message: '该记录已处理，无需重复处理'
      });
    }

    // 处理记录
    const result = await weaponService.processSingleRecord(record);

    res.json(result);
  } catch (error) {
    console.error('处理记录失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * POST /api/weapons/process-batch
 * 批量处理记录
 */
router.post('/process-batch', async (req, res) => {
  try {
    const { batchSize = 10 } = req.body;

    console.log(`开始批量处理，批次大小: ${batchSize}`);

    const result = await weaponService.processBatch(parseInt(batchSize));

    res.json(result);
  } catch (error) {
    console.error('批量处理失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * GET /api/weapons/detail/:id
 * 获取装备详情（包含基本信息、战技指标、使用用户）
 */
router.get('/detail/:id', async (req, res) => {
  try {
    const { id } = req.params;

    // 获取原始记录
    const [rawRecords] = await pool.execute(
      'SELECT * FROM raw_weapons WHERE id = ?',
      [id]
    );

    if (rawRecords.length === 0) {
      return res.status(404).json({
        success: false,
        message: '记录不存在'
      });
    }

    const rawRecord = rawRecords[0];

    // 获取基本信息
    const [basicInfo] = await pool.execute(
      'SELECT * FROM processed_weapons WHERE raw_weapon_id = ?',
      [id]
    );

    // 获取战技指标（平面数据）
    const [specifications] = await pool.execute(
      'SELECT * FROM weapon_specifications WHERE raw_weapon_id = ? ORDER BY level, sort_order',
      [id]
    );

    // 将平面数据转换为树形结构
    const specificationsTree = buildSpecificationsTree(specifications);

    // 获取使用用户
    const [users] = await pool.execute(
      'SELECT * FROM weapon_users WHERE raw_weapon_id = ?',
      [id]
    );

    res.json({
      success: true,
      rawRecord,
      basicInfo: basicInfo[0] || null,
      specifications: specificationsTree,
      specificationsFlat: specifications || [], // 保留平面数据供兼容
      users: users || []
    });
  } catch (error) {
    console.error('获取装备详情失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * GET /api/weapons/audit/pending
 * 获取待审核记录列表
 */
router.get('/audit/pending', async (req, res) => {
  try {
    const { page = 1, pageSize = 20 } = req.query;
    const offset = (parseInt(page) - 1) * parseInt(pageSize);

    // 获取总数
    const [countResult] = await pool.execute(`
      SELECT COUNT(*) as total 
      FROM raw_weapons 
      WHERE process_status = 'completed' AND audit_status = 'pending'
    `);
    const total = countResult[0].total;

    // 获取分页数据
    const [records] = await pool.execute(`
      SELECT 
        r.*,
        p.chinese_name,
        p.english_name,
        p.category,
        p.origin_country
      FROM raw_weapons r
      LEFT JOIN processed_weapons p ON r.id = p.raw_weapon_id
      WHERE r.process_status = 'completed' AND r.audit_status = 'pending'
      ORDER BY r.id DESC
      LIMIT ? OFFSET ?
    `, [parseInt(pageSize), offset]);

    res.json({
      success: true,
      data: records,
      total,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(total / parseInt(pageSize))
    });
  } catch (error) {
    console.error('获取待审核记录失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * POST /api/weapons/audit/submit
 * 提交审核
 */
router.post('/audit/submit', async (req, res) => {
  try {
    const { rawWeaponId, auditStatus, comment, updatedData } = req.body;

    if (!rawWeaponId || !auditStatus) {
      return res.status(400).json({
        success: false,
        message: '缺少必填参数'
      });
    }

    const auditorName = req.user.realName;
    const auditorId = req.user.employeeId;

    console.log(`审核装备，ID: ${rawWeaponId}, 状态: ${auditStatus}, 审核人: ${auditorName}`);

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 如果有更新数据，先更新处理后的数据
      if (updatedData && auditStatus === 'approved') {
        // 更新基本信息
        if (updatedData.basicInfo) {
          const basic = updatedData.basicInfo;
          await connection.execute(`
            UPDATE processed_weapons
            SET 
              origin_country = ?,
              category = ?,
              chinese_name = ?,
              english_name = ?,
              chinese_intro = ?,
              english_intro = ?,
              contractor = ?,
              service_time = ?,
              development_background = ?,
              construction_history = ?,
              service_history = ?,
              structural_features = ?,
              equipment = ?,
              power_system = ?,
              status = ?,
              updated_at = NOW()
            WHERE raw_weapon_id = ?
          `, [
            basic.origin_country, basic.category, basic.chinese_name, basic.english_name,
            basic.chinese_intro, basic.english_intro, basic.contractor, basic.service_time,
            basic.development_background, basic.construction_history, basic.service_history,
            basic.structural_features, basic.equipment, basic.power_system, basic.status,
            rawWeaponId
          ]);
        }

        // 更新战技指标（删除后重新插入）
        if (updatedData.specifications && Array.isArray(updatedData.specifications)) {
          await connection.execute(
            'DELETE FROM weapon_specifications WHERE raw_weapon_id = ?',
            [rawWeaponId]
          );

          // 注意：审核页面暂时支持平面结构更新，树形结构更新待实现
          for (let i = 0; i < updatedData.specifications.length; i++) {
            const spec = updatedData.specifications[i];
            const nodeType = spec.node_type || 'indicator';
            await connection.execute(`
              INSERT INTO weapon_specifications 
              (raw_weapon_id, parent_id, level, node_type, indicator_chinese, indicator_english, 
               indicator_value, sort_order)
              VALUES (?, NULL, 1, ?, ?, ?, ?, ?)
            `, [rawWeaponId, nodeType, spec.indicator_chinese, spec.indicator_english, 
                spec.indicator_value, i]);
          }
        }

        // 更新使用用户（删除后重新插入）
        if (updatedData.users && Array.isArray(updatedData.users)) {
          await connection.execute(
            'DELETE FROM weapon_users WHERE raw_weapon_id = ?',
            [rawWeaponId]
          );

          for (const user of updatedData.users) {
            await connection.execute(`
              INSERT INTO weapon_users 
              (raw_weapon_id, country, variant, operator_chinese, operator_english, operator_intro, order_quantity)
              VALUES (?, ?, ?, ?, ?, ?, ?)
            `, [rawWeaponId, user.country, user.variant, user.operator_chinese,
                user.operator_english, user.operator_intro, user.order_quantity]);
          }
        }
      }

      // 更新审核状态
      await connection.execute(`
        UPDATE raw_weapons
        SET 
          audit_status = ?,
          audit_time = NOW(),
          auditor_name = ?,
          auditor_id = ?,
          audit_comment = ?
        WHERE id = ?
      `, [auditStatus, auditorName, auditorId, comment || null, rawWeaponId]);

      await connection.commit();
      connection.release();

      console.log(`✓ 审核完成: ${auditStatus}`);

      res.json({
        success: true,
        message: '审核成功'
      });
    } catch (error) {
      await connection.rollback();
      connection.release();
      throw error;
    }
  } catch (error) {
    console.error('审核失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * GET /api/weapons/list
 * 获取装备列表（已审核通过）
 */
router.get('/list', async (req, res) => {
  try {
    const { page = 1, pageSize = 20, category, originCountry, keyword } = req.query;
    const offset = (parseInt(page) - 1) * parseInt(pageSize);

    // 构建查询条件
    let whereConditions = ['r.audit_status = ?'];
    let queryParams = ['approved'];

    if (category) {
      whereConditions.push('p.category = ?');
      queryParams.push(category);
    }

    if (originCountry) {
      whereConditions.push('p.origin_country = ?');
      queryParams.push(originCountry);
    }

    if (keyword) {
      whereConditions.push('(p.chinese_name LIKE ? OR p.english_name LIKE ?)');
      queryParams.push(`%${keyword}%`, `%${keyword}%`);
    }

    const whereClause = whereConditions.join(' AND ');

    // 获取总数
    const [countResult] = await pool.execute(`
      SELECT COUNT(*) as total 
      FROM raw_weapons r
      INNER JOIN processed_weapons p ON r.id = p.raw_weapon_id
      WHERE ${whereClause}
    `, queryParams);
    const total = countResult[0].total;

    // 获取分页数据
    const [records] = await pool.execute(`
      SELECT 
        r.id,
        r.audit_time,
        p.origin_country,
        p.category,
        p.chinese_name,
        p.english_name,
        p.chinese_intro,
        p.thumbnail,
        p.service_time,
        p.status
      FROM raw_weapons r
      INNER JOIN processed_weapons p ON r.id = p.raw_weapon_id
      WHERE ${whereClause}
      ORDER BY r.audit_time DESC
      LIMIT ? OFFSET ?
    `, [...queryParams, parseInt(pageSize), offset]);

    res.json({
      success: true,
      data: records,
      total,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(total / parseInt(pageSize))
    });
  } catch (error) {
    console.error('获取装备列表失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * PUT /api/weapons/:id
 * 更新装备信息
 */
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { basicInfo, specifications, users } = req.body;

    console.log(`更新装备信息，ID: ${id}`);

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 更新基本信息
      if (basicInfo) {
        await connection.execute(`
          UPDATE processed_weapons
          SET 
            origin_country = ?,
            category = ?,
            chinese_name = ?,
            english_name = ?,
            chinese_intro = ?,
            english_intro = ?,
            contractor = ?,
            service_time = ?,
            development_background = ?,
            construction_history = ?,
            service_history = ?,
            structural_features = ?,
            equipment = ?,
            power_system = ?,
            status = ?,
            updated_at = NOW()
          WHERE raw_weapon_id = ?
        `, [
          basicInfo.origin_country, basicInfo.category, basicInfo.chinese_name, basicInfo.english_name,
          basicInfo.chinese_intro, basicInfo.english_intro, basicInfo.contractor, basicInfo.service_time,
          basicInfo.development_background, basicInfo.construction_history, basicInfo.service_history,
          basicInfo.structural_features, basicInfo.equipment, basicInfo.power_system, basicInfo.status,
          id
        ]);
      }

      // 更新战技指标
      if (specifications && Array.isArray(specifications)) {
        await connection.execute(
          'DELETE FROM weapon_specifications WHERE raw_weapon_id = ?',
          [id]
        );

        // 注意：审核页面暂时支持平面结构更新，树形结构更新待实现
        for (let i = 0; i < specifications.length; i++) {
          const spec = specifications[i];
          const nodeType = spec.node_type || 'indicator';
          await connection.execute(`
            INSERT INTO weapon_specifications 
            (raw_weapon_id, parent_id, level, node_type, indicator_chinese, indicator_english, 
             indicator_value, sort_order)
            VALUES (?, NULL, 1, ?, ?, ?, ?, ?)
          `, [id, nodeType, spec.indicator_chinese, spec.indicator_english, 
              spec.indicator_value, i]);
        }
      }

      // 更新使用用户
      if (users && Array.isArray(users)) {
        await connection.execute(
          'DELETE FROM weapon_users WHERE raw_weapon_id = ?',
          [id]
        );

        for (const user of users) {
          await connection.execute(`
            INSERT INTO weapon_users 
            (raw_weapon_id, country, variant, operator_chinese, operator_english, operator_intro, order_quantity)
            VALUES (?, ?, ?, ?, ?, ?, ?)
          `, [id, user.country, user.variant, user.operator_chinese,
              user.operator_english, user.operator_intro, user.order_quantity]);
        }
      }

      await connection.commit();
      connection.release();

      console.log(`✓ 装备信息更新成功`);

      res.json({
        success: true,
        message: '更新成功'
      });
    } catch (error) {
      await connection.rollback();
      connection.release();
      throw error;
    }
  } catch (error) {
    console.error('更新装备信息失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * POST /api/weapons/reprocess/:id
 * 重新解析单条记录
 */
router.post('/reprocess/:id', async (req, res) => {
  try {
    const { id } = req.params;

    console.log(`\n========== 开始重新解析装备记录 ID: ${id} ==========`);

    // 获取原始记录
    const [rawRecords] = await pool.execute(
      'SELECT * FROM raw_weapons WHERE id = ?',
      [id]
    );

    if (rawRecords.length === 0) {
      return res.status(404).json({
        success: false,
        message: '记录不存在'
      });
    }

    const rawRecord = rawRecords[0];
    console.log(`找到原始记录: ${rawRecord.name}`);

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 删除旧的处理后数据
      console.log('删除旧的处理后数据...');
      await connection.execute(
        'DELETE FROM processed_weapons WHERE raw_weapon_id = ?',
        [id]
      );
      await connection.execute(
        'DELETE FROM weapon_specifications WHERE raw_weapon_id = ?',
        [id]
      );
      await connection.execute(
        'DELETE FROM weapon_users WHERE raw_weapon_id = ?',
        [id]
      );

      // 重置处理状态
      await connection.execute(
        'UPDATE raw_weapons SET process_status = ?, process_time = NULL, process_error = NULL WHERE id = ?',
        ['pending', id]
      );

      await connection.commit();
      connection.release();

      // 重新处理记录
      console.log('开始重新处理记录...');
      const result = await weaponService.processSingleRecord(rawRecord);

      if (result.success) {
        console.log('✓ 重新解析成功');

        // 获取新的处理后数据
        const [newBasicInfo] = await pool.execute(
          'SELECT * FROM processed_weapons WHERE raw_weapon_id = ?',
          [id]
        );
        const [newSpecifications] = await pool.execute(
          'SELECT * FROM weapon_specifications WHERE raw_weapon_id = ? ORDER BY level, sort_order',
          [id]
        );
        const newSpecificationsTree = buildSpecificationsTree(newSpecifications);
        const [newUsers] = await pool.execute(
          'SELECT * FROM weapon_users WHERE raw_weapon_id = ?',
          [id]
        );

        res.json({
          success: true,
          message: '重新解析成功',
          data: {
            basicInfo: newBasicInfo[0] || null,
            specifications: newSpecificationsTree || [],
            specificationsFlat: newSpecifications || [], // 保留平面数据
            users: newUsers || []
          }
        });
      } else {
        throw new Error(result.error || '处理失败');
      }
    } catch (error) {
      await connection.rollback();
      connection.release();
      throw error;
    }
  } catch (error) {
    console.error('✗ 重新解析失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * DELETE /api/weapons/:id
 * 删除待处理记录
 */
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const result = await weaponService.deleteRecord(parseInt(id));
    res.json(result);
  } catch (error) {
    console.error('删除记录失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * GET /api/weapons/statistics
 * 获取处理统计
 */
router.get('/statistics', async (req, res) => {
  try {
    const result = await weaponService.getProcessStatistics();
    res.json(result);
  } catch (error) {
    console.error('获取统计失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

module.exports = router;

